package com.lwt.gulimall.product.exception;

import com.lwt.gulimall.common.exception.ErrorMessageEnum;
import com.lwt.gulimall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author 刘伟涛
 * @Date 2024/3/4 10:46
 **/
@Slf4j
@RestControllerAdvice
public class GulimallExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleMethodArgumentException(MethodArgumentNotValidException e){
        log.error("校验出现问题{},类型：{}", e.getMessage(),e.getClass());
        Map<String,String> map = new HashMap<>();
        BindingResult bindingResult = e.getBindingResult();
        bindingResult.getFieldErrors().forEach(item ->{
            map.put(item.getField(),item.getDefaultMessage());
        });
        return R.error(ErrorMessageEnum.VALID_EXCEPTION).put("data",map);
    }

    @ExceptionHandler(value = Exception.class)
    public R handleException(Exception e){
        log.error("校验出现问题{},类型：{}", e.getMessage(),e.getClass());
        return R.error();
    }
}
